package com.cangshi.controller;

import com.alibaba.fastjson.JSONObject;
import com.cangshi.entity.Pager;
import com.cangshi.entity.PagerSetting;
import com.cangshi.entity.User;
import com.cangshi.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by Eoly on 2017/6/5.
 */
@Controller
@RequestMapping("/")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    PagerSetting pagerSetting;

    /**
     * [GET:/users]
     * 用户所有信息页面
     * 按用户偏移量获取
     *
     * @param model
     * @param offset
     * @param keywords
     * @return
     */
    @RequiresPermissions("user:vip")
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public String showUsers(
            Model model,
            @RequestParam(value = "pager.offset", required = false) Integer offset,
            @RequestParam(required = false) String keywords
    ) {
        if (offset == null) {
            offset = 0;
        }
        Integer pageSize = pagerSetting.getPageSize();
        List<User> users = userService.getUsersWithKeywords(offset, pageSize, keywords);
        Integer userSize = userService.getUserVolumeWithKeywords(keywords);
        Pager<List> pager = new Pager<List>(users, pageSize, userSize, offset);
        pager.setUrl("users");
        pager.addParam("keywords", keywords);
        model.addAttribute("pager", pager);
        return "user/list";
    }

    /**
     * [GET:/user-list]
     * 用户所有信息页面
     * 按页获取
     *
     * @param model
     * @param page
     * @param keywords
     * @return
     */
    @RequestMapping(value = "/user-list", method = RequestMethod.GET)
    public String showUserList(
            Model model,
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(required = false) String keywords
    ) {
        Integer pageSize = pagerSetting.getPageSize();
        if (page == null) {
            page = 1;
        }
        model.addAttribute("page", userService.getUsersByPageWithKeywords(page, pageSize, keywords));
        model.addAttribute("keywords", keywords);
        return "user/list_two";
    }

    /**
     * [POST:/users]
     * 添加用户逻辑
     *
     * @param model
     * @param user
     * @return
     */
    @RequiresPermissions("user:admin")
    @RequestMapping(value = "/users", method = RequestMethod.POST)
    public String addUser(
            Model model,
            @Validated User user,
            BindingResult result
    ) {
        if (result.hasErrors()) {
            return "/user/register";
        }
        if (userService.addUser(user)) {
            model.addAttribute("keywords", user.getUserDisplay());
        }

        return "redirect:/users";
    }

    /**
     * [GET:/users/{id}]
     * 单个id用户页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
    public String showUser(
            Model model,
            @PathVariable("id") String id
    ) {


        return "user";
    }


    /**
     * [PUT:/users/{id}]
     * JSON
     * 更新一个用户
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequiresPermissions("user:admin")
    @RequestMapping(value = "/users/{id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public String updateUser(
            @PathVariable Integer id,
            @RequestBody User user,
            @RequestParam(required = false) Integer type
    ) {
        if (type == null) {
            type = 0;
        }

        final int UPDATE_BASE = 0;
        final int UPDATE_PASSWORD = 1;
        final int UPDATE_STATUS = 2;

        JSONObject jsonObject = new JSONObject();
        user.setUserId(id);
        switch (type) {
            default:
            case UPDATE_BASE: {
                userService.editUserBaseInfo(user);
                jsonObject.put("error", 0);
                jsonObject.put("msg", "修改成功");
                return jsonObject.toString();
            }
            case UPDATE_PASSWORD: {
                userService.changePassword(user.getUserId(), user.getUserPass());
                jsonObject.put("error", 0);
                jsonObject.put("msg", "修改成功");
                return jsonObject.toString();
            }
            case UPDATE_STATUS: {
                userService.editUserStatus(user);
                jsonObject.put("error", 0);
                jsonObject.put("msg", "修改成功");
                return jsonObject.toString();
            }
        }
    }


    /**
     * [DELETE:/users/{id}]
     * 删除一个用户
     * JSON
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequiresPermissions("user:admin")
    @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE, produces = "application/json;charset=utf-8")
    public String deleteUser(
            @PathVariable Integer id
    ) {
        JSONObject jsonObject = new JSONObject();
        userService.deleteUserById(id);
        jsonObject.put("error", 0);
        jsonObject.put("msg", "删除成功");
        return jsonObject.toString();
    }
}
